package com.zzw.junit5demo;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;


/**
 * @author zzw
 * @version 1.0
 * @title SharedTempDirectoryDemo
 * @description <共享临时目录>
 * @datetime 2023-06-13 21:34
 */
public class SharedTempDirectoryDemo {

    // /var/folders/sw/z5p8lrqj4lqb_q8r1c02v92h0000gn/T/junit828515920328953492/
    @TempDir
    static Path sharedTempDir;

    @Test
    void writeItemsToFile() throws IOException {
        Path file = sharedTempDir.resolve("test.txt");
        FileWriter fw = new FileWriter(file.toFile());
        fw.write("a,b,c");
        fw.close();
        System.out.println(file);
        System.out.println(Files.readAllLines(file));
        // new ListWriter(file).write("a", "b", "c");
        assertEquals(Collections.singletonList("a,b,c"), Files.readAllLines(file));
    }

    @Test
    void anotherTestThatUsesTheSameTempDir() {
        // use sharedTempDir
    }

    @Test
    void copyFileFromSourceToTarget(@TempDir Path source, @TempDir Path target) throws IOException {
        Path sourceFile = source.resolve("test.txt");
        // new ListWriter(sourceFile).write("a", "b", "c");
        FileWriter fw = new FileWriter(sourceFile.toFile());
        fw.write("a,b,c");
        fw.close();

        Path targetFile = Files.copy(sourceFile, target.resolve("test.txt"));

        assertNotEquals(sourceFile, targetFile);
        assertEquals(Collections.singletonList("a,b,c"), Files.readAllLines(targetFile));
    }
}
